package com.futong.cloud.function.client;

import com.alibaba.fastjson.JSONObject;
import com.futong.cloud.action.ActionConsumer;
import com.futong.cloud.action.ActionException;
import com.futong.cloud.action.ActionModel;
import com.futong.cloud.dao.CloudClientMapper;
import com.futong.cloud.dao.entity.CloudClient;
import com.futong.cloud.utils.HttpUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.*;
import org.springframework.util.Base64Utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class H3C {
    static Pattern compile = Pattern.compile("\\{(.+?)\\}");
    public static ActionConsumer send= context -> {
        ActionModel action = context.getActionModel();
        String cloudId = context.getRequest().getString("cloudId");
        CloudClient client = CloudClientMapper.Mappers.client.selectById(cloudId);
        //发送请求
        if(StringUtils.isEmpty(client.getToken())){
            getToken(client);
        }
        Matcher matcher = compile.matcher(action.getCloudAction());
        StringBuffer sb=new StringBuffer();
        while (matcher.find()){
            String param=matcher.group(1);
            String replace;
            if("tenant_id".equalsIgnoreCase(param)){
                replace=client.getProjectId();
            }else if(context.getRequest().containsKey(param)){
                replace=context.getRequest().getString(param);
            }else{
                throw new ActionException("请求缺失参数:"+param,302);
            }
            matcher.appendReplacement(sb,replace);
        }
        matcher.appendTail(sb);
        String url=client.getServerProtocol()+"://"+client.getServerIp()+":"+client.getServerPort()+sb.toString();
        HttpHeaders headers=new HttpHeaders();
        headers.set("x-Auth-Token",client.getToken());
        HttpEntity<?> httpEntity=context.getRequest().containsKey("data")?new HttpEntity<>(context.getRequest().getJSONObject("data"),headers):new HttpEntity<>(headers);
        ResponseEntity<JSONObject> responseEntity = HttpUtils.exchange(url, HttpMethod.resolve(action.getCloudMethod()), httpEntity, JSONObject.class);
        //认证失败,token可能过期
        if(HttpStatus.UNAUTHORIZED==responseEntity.getStatusCode()){
            getToken(client);//重新刷新token
            responseEntity = HttpUtils.exchange(url, HttpMethod.resolve(action.getCloudMethod().toUpperCase()), httpEntity, JSONObject.class);
        }
        System.out.println(responseEntity);
        context.setResponse(responseEntity.getBody());
    };
    private static void getToken(CloudClient client){
        String url=client.getServerProtocol()+"://"+client.getServerIp()+":"+client.getServerPort()+client.getAuthenticationUrl();
        JSONObject requestBody=new JSONObject();
        requestBody.put("username",client.getUsername());
        requestBody.put("password", Base64Utils.encodeToString(client.getPassword().getBytes()));
        requestBody.put("domain","default");
        ResponseEntity<JSONObject> responseEntity = HttpUtils.post(url, requestBody, JSONObject.class);
        if(HttpStatus.OK==responseEntity.getStatusCode()){
            JSONObject responseBody=responseEntity.getBody();
            if(responseBody.getBoolean("status")) {
                client.setProjectId(responseBody.getJSONObject("res").getJSONObject("user").getString("default_project_id"));
                client.setProjectName(responseBody.getJSONObject("res").getJSONObject("user").getString("project_name"));
                client.setToken(responseBody.getJSONObject("res").getString("token"));
                CloudClientMapper.Mappers.client.updateById(client);
            }else{
                throw new ActionException("H3C账户认证失败!失败原因:"+responseBody.getString("msg"),302);
            }
        }else{
            throw new ActionException("H3C账户认证请求失败!账户名称:"+client.getUsername(),500);
        }
    }

    public static void main(String[] args) {
        Matcher matcher = compile.matcher("/os/compute/v1/v2/{tenant_id}/os-keypairs/{server_id}");
        while (matcher.find()){
            String param=matcher.group(1);
            System.out.println(param);
        }
    }
}
